package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.dao.UserAndMenusDao;
import com.itheima.pojo.Menu;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.*;

@Service
public class UserAndMenusSrevcieImpl implements UserAndMenusSrevcie {

    @Autowired
    UserAndMenusDao userAndMenusDao;

    @Override
    public List<Map<String, Object>> findAll(String username) {

        List<Map<String, Object>> list =userAndMenusDao.findParentList(username);

        List<Map<String, Object>> list2 =userAndMenusDao.findChildrenList(username);


        Integer s=0 ;
        //保存子菜单List
        Map<Integer,List<Map<String, Object>>> map2 = new HashMap<>();

        //子菜单path截取 “/” “-”中间的数字作为map2的key值
        for (int j = 0; j < list2.size(); j++) {
            String path = list2.get(j).get("path").toString();
            if(path.indexOf("/")!=-1) {
                //截取  /1-2  得到 1
                s = Integer.valueOf(path.substring(path.indexOf("/") + 1, path.indexOf("-")));
            }else{
                //必须有 “/”    “-” 没判断
                System.out.println("数据库数据格式不正确");
            }
            //如果没有这个key值
            if(!map2.containsKey(s)){
                //向map2添加新集合用来保存子菜单
                map2.put(s,new ArrayList<Map<String, Object>>());
            }
            //保存子菜单到map2对应key值的list集合内
            map2.get(s).add(list2.get(j));
        }
        //遍历父菜单
        for (int i = 0; i < list.size(); i++) {
            //取出所有key值
            Set<Integer> keySet = map2.keySet();
            for (Integer integer:keySet) {
                //判断父菜单path与map2的key值是否相等  如果相等，则把map2内的list存到list
                for (int j = 0; j < list.size(); j++) {
                    if(Integer.valueOf(list.get(j).get("path").toString())==integer){
                        list.get(j).put("children",map2.get(integer));
                        break;
                    }
                }
            }
        }


        System.out.println("+++++++++++++++++++++++++++++++++++++"+list);
        return list;
    }
}
